<template>
  <a-modal
    :title="modalTitle"
    :width="600"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item :label="$t('menu.dict').toLowerCase()">
          <span>{{ dictClass ? dictClass.name : '' }}</span>
        </a-form-model-item>

        <a-form-model-item
          :label="$t('technology.dict.key')"
          prop="key"
          :rules="[
            {
              validator: validator.keyValidator,
              trigger: 'change'
            },
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.dict.key').toLowerCase() }),
              whitespace: true,
              trigger: 'change'
            }
          ]"
        >
          <s-input :limit="64" v-model.trim="form.key" />
        </a-form-model-item>

        <a-form-model-item
          :label="$t('technology.dict.value')"
          prop="value"
          :rules="[
            {
              validator: validator.valueValidator,
              trigger: 'change'
            },
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.dict.value').toLowerCase() }),
              whitespace: true,
              trigger: 'change'
            }
          ]"
        >
          <s-input :limit="155" v-model.trim="form.value" />
        </a-form-model-item>
        <a-form-model-item :label="$t('common.description')" prop="description">
          <s-input :limit="255" v-model.trim="form.description" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { addDictDetail, updateDictDetail, validateDictDetailUnique } from '@/api/technology/dict/dict';
import { asyncValidateMixin } from '@/utils/mixin';
import { SInput } from '@/components';

export default {
  name: 'DictDetailForm',
  mixins: [asyncValidateMixin],
  components: {
    SInput
  },
  data() {
    return {
      record: null,
      dictClass: null,
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 6
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 16
        }
      },
      visible: false,
      confirmLoading: false,
      form: {
        key: '',
        value: '',
        description: ''
      }
    };
  },
  computed: {
    modalTitle() {
      if (this.record) {
        return this.$t('common.editRecord', {
          name: this.$t('technology.dict.dictDetail').toLowerCase()
        });
      }
      return this.$t('common.addNewRecord', {
        name: this.$t('technology.dict.dictDetail').toLowerCase()
      });
    }
  },
  created() {
    this.$_asyncValidateMixin_init([
      {
        fieldName: 'key',
        caller: validateDictDetailUnique,
        extraParams: () => ({
          techDataDictionaryId: this.dictClass ? this.dictClass.id : '',
          id: this.record ? this.record.id : ''
        })
      },
      {
        fieldName: 'value',
        caller: validateDictDetailUnique,
        extraParams: () => ({
          techDataDictionaryId: this.dictClass ? this.dictClass.id : '',
          id: this.record ? this.record.id : ''
        })
      }
    ]);
  },

  methods: {
    add(classItem) {
      this.dictClass = {
        ...classItem
      };
      this.visible = true;
    },
    // 不编辑
    edit(record) {
      this.visible = true;
      this.form = {
        ...record
      };
    },

    handleCancel() {
      this.visible = false;
      this.confirmLoading = false;
      this.dictClass = null;
      this.record = null;
      this.form = {
        key: '',
        value: '',
        description: ''
      };
      this.$refs.form.resetFields();
      this.$_asyncValidateMixin_resetFields();
    },

    handleSubmit() {
      if (!this.canSubmit) {
        return;
      }
      this.confirmLoading = true;
      const fieldNames = this.$_asyncValidateMixin_fieldsFilter({
        key: '',
        value: ''
      });
      const validatePromise = fieldNames.map(fieldName => {
        const p = new Promise((resolve, reject) => {
          this.$refs.form.validateField(fieldName, errorMessage => {
            if (!errorMessage) {
              resolve();
            } else {
              reject(errorMessage);
            }
          });
        });
        return p;
      });
      Promise.all(validatePromise)
        .then(() => {
          const { key, value, description } = this.form;
          const params = {
            key,
            value,
            description,
            techDataDictionaryId: this.dictClass.id
          };
          let api = null;
          if (this.record) {
            params.id = this.record.id;
            api = updateDictDetail;
          } else {
            api = addDictDetail;
          }
          api(params)
            .then(res => {
              this.$message.success(res.message);
              this.$emit('ok');
              this.handleCancel();
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        })
        .catch(() => {
          this.confirmLoading = false;
        });
    }
  }
};
</script>
